 
package com.zdkj.subway.rca.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.DateUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zdkj.common.core.exceltools.MultipartFileToFile;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.rca.entity.SwCkDistinctPaymentQrTmp;
import com.zdkj.subway.rca.entity.SwCkDistinctPaymentQr;
import com.zdkj.subway.rca.mapper.SwCkDistinctPaymentQrTmpMapper;
import com.zdkj.subway.rca.service.SwCkDistinctPaymentQrTmpService;
import com.zdkj.subway.rca.service.SwCkDistinctPaymentService;
import com.zdkj.subway.rca.service.SwCkDistinctPaymentQrService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.time.ZoneId;
import java.util.*;

/**
 * 多元化支付平台审核-微信支付宝银联临时表
 *
 * @author stw
 * @date 2020-10-29 10:35:24
 */
@Service
public class SwCkDistinctPaymentQrTmpServiceImpl extends ServiceImpl<SwCkDistinctPaymentQrTmpMapper, SwCkDistinctPaymentQrTmp> implements SwCkDistinctPaymentQrTmpService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SwCkDistinctPaymentQrTmpServiceImpl.class);
    private String parsePattern = "yyyy-MM-dd";
    @Autowired
    private SwCkDistinctPaymentService swCkDistinctPaymentService;
    @Autowired
    private SwCkDistinctPaymentQrService swCkDistinctPaymentQrService;

    @Override
    public Boolean saveBatchWithExcel(final File excelFile) throws Exception {
        List<Map<Integer, String>> listMap = EasyExcel.read(excelFile).sheet().headRowNumber(4).doReadSync();
        List<Map<String,String>> lineMap = swCkDistinctPaymentService.selectLineMap();
        List<Map<String,String>> stationMap = swCkDistinctPaymentService.selectStationMap();

        if (CollectionUtil.isNotEmpty(listMap)) {
            List<SwCkDistinctPaymentQrTmp> listDb = new ArrayList<>();
            MultipartFileToFile.delteTempFile(excelFile);
            for (int m = 0; m < listMap.size(); m++) {
                Map<Integer, String> data = listMap.get(m);
                // 返回每条数据的键值对 表示所在的列 和所在列的值
                LOGGER.info("读取到数据:{}", JSON.toJSONString(data));
                if(data.get(1).contains("小计") || data.get(2).contains("小计")){
                    continue;
                }
                SwCkDistinctPaymentQrTmp tmpObj = new SwCkDistinctPaymentQrTmp();
                tmpObj.setTradeDateTmp(data.get(0));//交易日期
                tmpObj.setLineCodeTmp(data.get(1));
                tmpObj.setStationCodeTmp(data.get(2));
				if(data.get(0)!=null && !data.get(0).equals("") && data.get(0).indexOf("小计")>-1){
                	continue;
                }
				if(data.get(0)==null){
				    break;
                }

//                原来模版内容  日期，线路、站点、微信、支付宝、银联、银联自发码
//                tmpObj.setWechatMoneyTmp(data.get(3));
//                tmpObj.setAlipayMoneyTmp(data.get(4));
//
//                tmpObj.setBankMoneyTmp(data.get(5));
//                tmpObj.setBankZfmMoneyTmp(data.get(6));
                //20241008之前的序号
				/*
				String weChatReal= data.get(6);
                String weChatApp = data.get(12);
                String alipayReal = data.get(4);
                String alipayApp = data.get(10);
                String bankReal = data.get(8);
                String bankApp = data.get(18);//原来14，后加入了微信小程序
				String wechatapp = data.get(14);//微信小程序
				String wechatappDiscount = data.get(16);//微信小程序（优惠）*/
				//20241009根据新模板进行调整
			    String weChatReal= data.get(8);
                String weChatApp = data.get(10);
                String alipayReal = data.get(4);
                String alipayApp = data.get(6);
                String bankReal = data.get(12);
                String bankApp = data.get(14);
				String wechatapp = "0.00";//data.get(14);//微信小程序
				String wechatappDiscount = "0.00";//data.get(16);//微信小程序（优惠）
                BigDecimal longWechat = new BigDecimal(weChatReal).add(new BigDecimal(weChatApp));
                BigDecimal longAlipay = new BigDecimal(alipayReal).add(new BigDecimal(alipayApp));
                BigDecimal longBank = new BigDecimal(bankReal).add(new BigDecimal(bankApp));
				BigDecimal longWechatapp = new BigDecimal(wechatapp);//两者不需要累加
				BigDecimal longWechatappDiscount = new BigDecimal(wechatappDiscount);


                tmpObj.setWechatMoneyTmp(longWechat.toString());
                tmpObj.setAlipayMoneyTmp(longAlipay.toString());

                tmpObj.setBankMoneyTmp(longBank.toString());
                tmpObj.setBankZfmMoneyTmp("0.00");

				tmpObj.setWechatappMoneyTmp(wechatapp);
				tmpObj.setWechatappDiscountMoneyTmp(wechatappDiscount);

                if (StringUtils.isEmpty(tmpObj.getTradeDateTmp())) {
                    continue;
                }
                if (!parseDate(tmpObj.getTradeDateTmp())) {
                    continue;
                }
                final SwCkDistinctPaymentQrTmp obj = ObjectUtils.getDefaultObj(SwCkDistinctPaymentQrTmp.class);
                BeanUtils.copyProperties(tmpObj, obj, "deptId", "creatorId", "creatorName");
                checkErr(obj,lineMap,stationMap);
                listDb.add(obj);

            }
            Map<String, Object> columnMap = new HashMap<>();
            columnMap.put("CREATOR_ID", listDb.get(0).getCreatorId());
            this.baseMapper.deleteByMap(columnMap);
            return this.saveBatch(listDb);

        }

        return false;
    }

    private String getLineCode (List<Map<String,String>> lineMap,String lineName) {
        for (Map<String,String> map : lineMap){
            if(lineName.equals(map.get("NAME"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    private String getStationCode (List<Map<String,String>> stationMap,String stationName,String lineCode) {
        for (Map<String,String> map : stationMap){
            if(stationName.equals(map.get("NAME")) && lineCode.equals(map.get("LINE_CODE"))){
                return map.get("CODE");
            }
        }
        return "";
    }

    private void checkErr(SwCkDistinctPaymentQrTmp obj, List<Map<String,String>> lineMap, List<Map<String,String>> stationMap) {
        //更新字段
        String tradeDateTmp = obj.getTradeDateTmp();
        try {
            Date tradeDate = DateUtils.parseDate(tradeDateTmp, parsePattern);
            obj.setTradeDate(tradeDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate());
        } catch (Exception e) {
            obj.setErrMsg("交易日期 为空或格式错误");
        }

        if(StringUtils.isNotEmpty(obj.getLineCodeTmp())){
            String lineCode = getLineCode(lineMap,obj.getLineCodeTmp());
            if(StringUtils.isNotEmpty(lineCode)){
                obj.setLineCode(lineCode);
            } else {
                obj.setErrMsg("线路名称 为空或不规范");
            }

        } else {
            obj.setErrMsg("线路名称 为空");
        }

        if(StringUtils.isNotEmpty(obj.getStationCodeTmp()) && StringUtils.isNotEmpty(obj.getLineCode())){
            String stationCode = getStationCode(stationMap,obj.getStationCodeTmp(),obj.getLineCode());
            if(StringUtils.isNotEmpty(stationCode)){
                obj.setStationCode(stationCode);
            } else {
                obj.setErrMsg("车站名称 为空或不规范");
            }
        } else {
            obj.setErrMsg("车站名称 为空");
        }

        try {
            BigDecimal num = new BigDecimal("100");

            String wechatMoneyTmp = obj.getWechatMoneyTmp();
            BigDecimal wechatMoney = new BigDecimal(wechatMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatMoney = wechatMoney.multiply(num);
            obj.setWechatMoney(wechatMoney.longValue());

            String alipayMoneyTmp = obj.getAlipayMoneyTmp();
            BigDecimal alipayMoney = new BigDecimal(alipayMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            alipayMoney = alipayMoney.multiply(num);
            obj.setAlipayMoney(alipayMoney.longValue());

            String bankMoneyTmp = obj.getBankMoneyTmp();
            BigDecimal bankMoney = new BigDecimal(bankMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            bankMoney = bankMoney.multiply(num);
            obj.setBankMoney(bankMoney.longValue());

            String bankZfmMoneyTmp = obj.getBankZfmMoneyTmp();
            BigDecimal bankZfmMoney = new BigDecimal(bankZfmMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            bankZfmMoney = bankZfmMoney.multiply(num);
            obj.setBankZfmMoney(bankZfmMoney.longValue());

			String wechatappMoneyTmp = obj.getWechatappMoneyTmp();
            BigDecimal wechatappMoney = new BigDecimal(wechatappMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatappMoney = wechatappMoney.multiply(num);
            obj.setWechatappMoney(wechatappMoney.longValue());

			String wechatappDiscountMoneyTmp = obj.getWechatappDiscountMoneyTmp();
            BigDecimal wechatappDiscountMoney = new BigDecimal(wechatappDiscountMoneyTmp).setScale(2, BigDecimal.ROUND_HALF_UP);
            wechatappDiscountMoney = wechatappDiscountMoney.multiply(num);
            obj.setWechatappDiscountMoney(wechatappDiscountMoney.longValue());

        } catch (Exception e) {
            obj.setErrMsg("金额 为空或格式错误");
        }

        //判断数据是否存在
        SwCkDistinctPaymentQr swCkDistinctPaymentQr = new SwCkDistinctPaymentQr();
		swCkDistinctPaymentQr.setLineCode(obj.getLineCode());
        swCkDistinctPaymentQr.setStationCode(obj.getStationCode());
        swCkDistinctPaymentQr.setTradeDate(obj.getTradeDate());
        swCkDistinctPaymentQr.setDelFlag("0");
       
		int count= swCkDistinctPaymentQrService.count(Wrappers.query(swCkDistinctPaymentQr));
        if (count > 0 && StringUtils.isEmpty(obj.getErrMsg())) {
            obj.setErrMsg("数据已存在");
        }
		/*
        BeanUtils.copyProperties(obj, swCkDistinctPaymentQr, "deptId","creatorId","creatorName","createTime");
        List<SwCkDistinctPaymentQr> list = swCkDistinctPaymentQrService.list(Wrappers.query(swCkDistinctPaymentQr));
        if (list != null && !list.isEmpty()) {
            obj.setErrMsg("数据已存在");
        }
		*/
    }

    private boolean parseDate(String string) {
        boolean convertSuccess = true;
        if (string == null) {
            return false;
        }

        try {
            DateUtils.parseDate(string, parsePattern);
        } catch (ParseException e) {
            convertSuccess = false;
        }
        return convertSuccess;
    }

    @Override
    public void saveBatchWithExcelOk(Integer creatorId) {
        //导入先删除
        this.baseMapper.deleteBatchWithExcelOk(creatorId);
        //导入先删除再添加包括重复的
        this.baseMapper.saveBatchWithExcelOkRepeat(creatorId);
        //this.baseMapper.saveBatchWithExcelOk(creatorId);
        saveBatchWithExcelCancel(creatorId);
    }

    @Override
    public void saveBatchWithExcelCancel(Integer creatorId) {
        Map<String, Object> columnMap = new HashMap<>();
        columnMap.put("CREATOR_ID", creatorId);
        this.baseMapper.deleteByMap(columnMap);
    }
}
